package com.flying.arts.trade.domain.repository;

import com.flying.arts.common.domain.entity.Entity;
import com.flying.arts.trade.domain.definition.Side;
import com.flying.arts.trade.domain.entity.Trade;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository("buyTradeRepository")
public class InMemoryTradeRepository implements TradeRepository {
    private Map<Long, Trade> trades;

    public InMemoryTradeRepository() {
        this.trades = new HashMap<>();
        Trade trade = null;
        trade = new Trade((long) 1, "中国平安", Side.buy, 34.92, 2500, 34.92 * 2500, 20161220);
        trades.put((long) 1, trade);
        trade = new Trade((long) 2, "中国平安", Side.buy, 34.10, 2500, 34.10 * 2500, 20161014);
        trades.put((long) 2, trade);
        trade = new Trade((long) 3, "老白干", Side.buy, 22.49, 2500, 22.49 * 2500, 20170116);
        trades.put((long) 3, trade);
        trade = new Trade((long) 4, "老白干", Side.buy, 23.47, 2500, 23.47 * 2500, 20161222);
        trades.put((long) 4, trade);
    }

    @Override
    public void add(Trade entity) {
        trades.put(entity.getId(), entity);
    }

    @Override
    public void remove(Long id) {
        if (trades.containsKey(id)) trades.remove(id);
    }

    @Override
    public void update(Trade entity) {
        if (trades.containsKey(entity.getId())) trades.put(entity.getId(), entity);
    }

    @Override
    public boolean contains(Long id) {
        return trades.containsKey(id);
    }

    @Override
    public Entity get(Long id) {
        return trades.get(id);
    }

    @Override
    public Collection<Trade> findByStockName(String name) {
        Collection<Trade> trades = new ArrayList<>();
        int noOfChars = name.length();
        this.trades.forEach((k, v) -> {
            if (v.getStockName().toLowerCase().contains(name.subSequence(0, noOfChars))) {
                trades.add(v);
            }
        });
        return trades;
    }

    @Override
    public Collection<Trade> getAll() {
        return trades.values();
    }
}
